// 云函数入口文件
const cloud = require('wx-server-sdk')

// 错误码
const ERROR_CODE = {
  NOT_FOUND: 10001,  // 画板不存在
  NOT_MEMBER: 10002, // 不是画板的成员
  PAREM_EMPTY: 10003, // 参数为空
  NOT_EDIT_AUTH: 10004, // 没有编辑权限
}

cloud.init()
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  let { OPENID } = cloud.getWXContext()
  try {
    const { data: drawBoardDatas } = await db.collection('drawBoards').where({
      [`members.${OPENID}`]: _.exists(true) // 如果 members 存在当前 OPENID, 返回
    }).field({
      _id: true,
      imgId: true,
      owner: true,
      title: true,
      members: true,
    }).get();
    
    for (let i = 0; i < drawBoardDatas.length; i++) {
      let drawBoardData = drawBoardDatas[i];
      drawBoardData.isOwner = drawBoardData.owner.openId === OPENID;
    }
    
    return {
      data: drawBoardDatas,
      code: 0,
      msg: 'success'
    }
  } catch (err) {
    return {
      code: 1,
      msg: err,
      data: {}
    }
  }
}